package com.spark.common.widget

import android.content.Context
import android.support.v4.widget.NestedScrollView
import android.util.AttributeSet
import android.util.Log
import android.view.GestureDetector
import android.view.GestureDetector.SimpleOnGestureListener
import android.view.MotionEvent
import android.view.View
import android.webkit.WebView
import android.widget.Scroller
import java.lang.reflect.Field

/**
 * 自定义ScrollView，解决：ScrollView嵌套ViewPager，导致ViewPager不能滑动的问题
 */
open class ViewPagerScrollView(context: Context, attrs: AttributeSet) : NestedScrollView(context, attrs) {
    private var mGestureDetector: GestureDetector
    private var Scroll_height = 0
    private var view_height = 0
    protected var scrollView_mScroller: Field? = null


    companion object {
        private val TAG = "ViewPagerScrollView"

        /**
         * 获取一个对象隐藏的属性，并设置属性为public属性允许直接访问
         *
         * @return [Field] 如果无法读取，返回null；返回的Field需要使用者自己缓存，本方法不做缓存�?
         */
        fun getDeclaredField(`object`: Any, field_name: String): Field? {
            var cla: Class<*> = `object`.javaClass
            var field: Field? = null
            while (cla != Any::class.java) {
                try {
                    field = cla.getDeclaredField(field_name)
                    field!!.isAccessible = true
                    return field
                } catch (e: Exception) {

                }

                cla = cla.superclass
            }
            return null
        }
    }

    init {
        mGestureDetector = GestureDetector(context, YScrollDetector())
        this.setFadingEdgeLength(0)
    }

    override fun onInterceptTouchEvent(ev: MotionEvent): Boolean {
        if (ev.action == MotionEvent.ACTION_DOWN) {
            stopAnim()
        }
        val ret = super.onInterceptTouchEvent(ev)
        val ret2 = mGestureDetector.onTouchEvent(ev)
        return ret && ret2
    }

    // Return false if we're scrolling in the x direction
    internal inner class YScrollDetector : SimpleOnGestureListener() {
        override fun onScroll(e1: MotionEvent, e2: MotionEvent, distanceX: Float, distanceY: Float): Boolean {
            return Math.abs(distanceY) > Math.abs(distanceX)
        }
    }

    override fun onScrollChanged(l: Int, t: Int, oldl: Int, oldt: Int) {
        var stop = false
        if (Scroll_height - view_height == t) {
            stop = true
        }
        if (t == 0 || stop) {
            try {
                if (scrollView_mScroller == null) {
                    scrollView_mScroller = getDeclaredField(this, "mScroller")
                }

                val ob = scrollView_mScroller!!.get(this)
                if (ob == null || ob !is Scroller) {
                    return
                }
                ob.abortAnimation()
            } catch (e: Exception) {
                Log.e(TAG, e.message)
            }

        }
        super.onScrollChanged(l, t, oldl, oldt)
    }

    private fun stopAnim() {
        try {
            if (scrollView_mScroller == null) {
                scrollView_mScroller = getDeclaredField(this, "mScroller")
            }

            val ob = scrollView_mScroller!!.get(this) ?: return
            val method = ob.javaClass.getMethod("abortAnimation")
            method.invoke(ob)
        } catch (ex: Exception) {
            Log.e(TAG, ex.message)
        }

    }

    override fun computeVerticalScrollRange(): Int {
        Scroll_height = super.computeVerticalScrollRange()
        return Scroll_height
    }

    override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) {
        super.onLayout(changed, l, t, r, b)
        if (changed) {
            view_height = b - t
        }
    }

    override fun requestChildFocus(child: View, focused: View?) {
        if (focused != null && focused is WebView) {
            return
        }
        super.requestChildFocus(child, focused)
    }
}